package com.ido.news.splashlibrary.util

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log


class CacheHelper(context: Context?, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, name, factory, version) {
    companion object {
        private val tableName = "JSON_CACHE"
        private val JSON = "JSON"
        val SQLVERSION = 1
        val DBNAME = "IDO_SPLASH_JSON_CACHE.db"
        var instance: CacheHelper? = null
        fun getInstance(context: Context?, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int): CacheHelper {
            if (instance == null) {
                synchronized(CacheHelper::class) {
                    if (instance == null) {
                        instance = CacheHelper(context, name, factory, version)
                    }
                }
            }
            return instance!!
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL("CREATE TABLE $tableName ($JSON TEXT NOT NULL)")
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {}

    fun setJson(json: String) {
        val cv = ContentValues()
        cv.put(JSON, json)
        clear()
        Log.e("增加", readableDatabase.insert(tableName, null, cv).toString())
    }

    fun getJson(): String? {
        var result: String? = null
        val c = readableDatabase.query(tableName, null,
                null,
                null, null, null, null)
        if (c.count > 0) {
            c.moveToFirst()
            result = c.getString(c.getColumnIndex(JSON))
        }
        return result
    }

    fun clear() {
        readableDatabase.execSQL("delete from $tableName")
    }

    fun dbClose() {
        if (readableDatabase != null) {
            if (readableDatabase.isOpen) {
                readableDatabase.close()
            }
        }
    }
}